package com.wurao.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import com.wurao.entity.Blogger;
import com.wurao.service.BloggerService;
import com.wurao.util.CryptographyUtil;
import com.wurao.util.StringUtil;
/**
 * 博主账号控制层
 * @author xxxx
 *
 */
@Controller
@RequestMapping("/blogger")
public class BloggerController {
	@Resource
	private BloggerService bloggerService;
	Logger logger=Logger.getLogger(BloggerController.class);
	
	
	@RequestMapping("/login")
	public String login(Blogger blogger,HttpServletRequest request){
		Subject subject=SecurityUtils.getSubject();	
		UsernamePasswordToken token=new UsernamePasswordToken(blogger.getUserName(), CryptographyUtil.md5(blogger.getPassword(),blogger.getUserName()));
		try{
			//System.out.println("开始登陆----------0");
			subject.login(token); // 登录验证
			request.getSession().setAttribute("loginName", blogger.getUserName());
			return "redirect:/admin/main.jsp";
		}catch(Exception e){
			//e.printStackTrace();
			request.setAttribute("blogger", blogger);
			request.setAttribute("errorInfo", "用户名或者密码错误！");
			return "login";
		}
	}
	
	
	/**
	 * QQ登录跳转
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/qqLogin")
	public void qqLogin(HttpServletRequest request,HttpServletResponse response) throws IOException {
		 response.setContentType("text/html;charset=utf-8");
        try {
			response.sendRedirect(new Oauth().getAuthorizeURL(request));
		} catch (QQConnectException e) {
			// TODO Auto-generated catch block
			new QQConnectException("跳转到QQ登录页面异常");
		}
	}
	
	/**
	 * QQ登录回调
	 * @param request
	 * @param response
	 * @return
	 * @throws QQConnectException
	 */
	@RequestMapping(value="QQCallBack")
	public String qqcallback(HttpServletRequest request,HttpServletResponse response) throws QQConnectException{
		response.setContentType("text/html;charset=utf-8");
		AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
		 String accessToken   = null;
		 String openID  = null;
		try {
			accessToken = accessTokenObj.getAccessToken();
			request.setAttribute("accessToken", accessToken);
			if (StringUtil.isEmpty(accessToken)) {
				System.out.println("没有获取到响应参数");
			}else{
				OpenID openIDObj =  new OpenID(accessToken);
				openID=openIDObj.getUserOpenID();
				UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
				UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
				if(userInfoBean != null && userInfoBean.getRet() == 0 && StringUtil.isEmpty(userInfoBean.getMsg())){
					System.out.println("欢迎你，代号为 " + openID + " 的用户!");
					System.out.println("黄钻等级： " + userInfoBean.isYellowYearVip());
					System.out.println("昵称： " + userInfoBean.getNickname());
					System.out.println("性别： " + userInfoBean.getGender());
					System.out.println("黄钻等级： " + userInfoBean.getLevel());
					System.out.println("会员 : " + userInfoBean.isVip());
					System.out.println("黄钻会员： " + userInfoBean.isYellowYearVip());
					System.out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL30() + "/>");
					System.out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL50() + "/>");
					System.out.println("<image src=" + userInfoBean.getAvatar().getAvatarURL100() + "/>");
					//获取用户成功
					Blogger blogger=bloggerService.getByUserOpenId(openID);
					
					if(blogger!=null){//存在该用户
						blogger.setNickName(filterEmoji(userInfoBean.getNickname()));
						blogger.setUserName(filterEmoji(userInfoBean.getNickname()));
						blogger.setPassword(CryptographyUtil.md5("123456", userInfoBean.getNickname()));
						bloggerService.update(blogger);
					}else{
						blogger=new Blogger();
						blogger.setNickName(filterEmoji(userInfoBean.getNickname()));
						blogger.setOpenId(openID);
						blogger.setSex(userInfoBean.getGender());
						blogger.setImageName(userInfoBean.getAvatar().getAvatarURL100());
						
						blogger.setPassword(CryptographyUtil.md5("123456", userInfoBean.getNickname()));
						blogger.setProfile(null);
						blogger.setSign(null);
						blogger.setUserName(filterEmoji(userInfoBean.getNickname()));
						bloggerService.add(blogger);
					}
					request.getSession().setAttribute("qqblogger", blogger);
					//存储用户信息
					System.out.println("调用成功了");
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/";
	}

	
	/**
	  * 将emoji表情替换成空串
	  *  
	  * @param source
	  * @return 过滤后的字符串
	  */
	 public static String filterEmoji(String source) {
	  if (source != null && source.length() > 0) {
	   return source.replaceAll("[\ud800\udc00-\udbff\udfff\ud800-\udfff]", "");
	  } else {
	   return source;
	  }
	 }
	 
	/**
	 * 关于博主
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/aboutMe")
	public ModelAndView aboutMe()throws Exception{
		ModelAndView mav=new ModelAndView();
		mav.addObject("pageTitle", "关于博主_勿扰博客");
		mav.addObject("mainPage", "foreground/blogger/info.jsp");
		mav.setViewName("mainTemp");
		return mav;
	}
	
	
	/**
	 * 背景颜色
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/color",method = RequestMethod.POST)
	@ResponseBody
	public String color(String color,HttpServletRequest request)throws Exception{
		request.getSession().setAttribute("color", color);
		return (String) request.getSession().getAttribute("color");
	}
}
